import { getUserInfo, userLogin } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  userInfo: {},
  token: getToken() || ''
}

const mutations = {
  myToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, newInfo) {
    // 等号前的值为state中定义的值
    state.userInfo = newInfo
  }
}

const actions = {
  async login(context, payload) {
    const res = await userLogin(payload)
    console.log(res)
    const token = res.data
    context.commit('myToken', token)
  },
  async getProfile(context) {
    const res = await getUserInfo()
    console.log(res)
    // context是将处理的数据发给mutations,括号中传递的参数是要接收的方法名,以及参数
    context.commit('setUserInfo', res.data)
    return res.data
  },
  logout(context) {
    context.commit('myToken', '')
    context.commit('setUserInfo', {})
    // 重置路由,解决重新登录时进入页面控制台的警告
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
